<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入预约人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker clearable
          v-model="queryParams.appointmentTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="接种地点" prop="location">
        <el-select v-model="queryParams.location" placeholder="请选择接种地点" clearable>
          <el-option label="社区医院" value="社区医院" />
          <el-option label="市人民医院" value="市人民医院" />
          <el-option label="市儿童医院" value="市儿童医院" />
          <el-option label="区疾控中心" value="区疾控中心" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.appointment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接种日期" prop="vaccinationDate">
        <el-date-picker clearable
          v-model="queryParams.vaccinationDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择接种日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="疫苗批次号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入疫苗批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['appointment:appointmentVaccination:add']"
        >疫苗预约</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['appointment:appointmentVaccination:remove']"
        >删除</el-button>
      </el-col>
    <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['appointment:appointmentVaccination:remove']"
          >删除</el-button> -->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentVaccinationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" />
      
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="身份证号" align="center" prop="userIdCard" />
      <el-table-column label="邮箱" align="center" prop="userEmail" />

      <el-table-column label="疫苗名称" align="center" prop="vaccineId">
        <template slot-scope="scope">
          <span>{{ getVaccineName(scope.row.vaccineId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.appointmentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接种地点" align="center" prop="location" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.appointment_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="接种日期" align="center" prop="vaccinationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.vaccinationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="疫苗批次号" align="center" prop="batchNumber" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['appointment:appointmentVaccination:edit']"
          >修改预约信息</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleCancel(scope.row)"
            v-hasPermi="['appointment:appointmentVaccination:edit']"
            v-if="scope.row.status === '0'"
          >取消预约</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['appointment:appointmentVaccination:remove']"
          >删除</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleVaccinate(scope.row)"
            v-hasPermi="['appointment:appointmentVaccination:remove']"
            v-if="scope.row.status === '0'"
          >接种</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约接种记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入预约人姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="userIdCard">
          <el-input v-model="form.userIdCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="form.userEmail" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="选择疫苗" prop="vaccineId">
          <el-select v-model="form.vaccineId" placeholder="请选择疫苗" :disabled="title.includes('修改')">
            <el-option
              v-for="item in vaccineOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable
            v-model="form.appointmentTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="接种地点" prop="location">
          <el-select v-model="form.location" placeholder="请选择接种地点">
            <el-option label="社区医院" value="社区医院" />
            <el-option label="市人民医院" value="市人民医院" />
            <el-option label="市儿童医院" value="市儿童医院" />
            <el-option label="区疾控中心" value="区疾控中心" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加接种弹窗 -->
    <el-dialog :title="'接种信息'" :visible.sync="vaccinateOpen" width="500px" append-to-body>
      <el-form ref="vaccinateForm" :model="vaccinateForm" :rules="vaccinateRules" label-width="80px">
        <el-form-item label="疫苗批次" prop="batchNumber">
          <el-input v-model="vaccinateForm.batchNumber" placeholder="请输入疫苗批次号" />
        </el-form-item>
        <el-form-item label="接种时间" prop="vaccinationDate">
          <el-date-picker
            clearable
            v-model="vaccinateForm.vaccinationDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择接种时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitVaccinateForm">确 定</el-button>
        <el-button @click="cancelVaccinate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppointmentVaccination, getAppointmentVaccination, delAppointmentVaccination, addAppointmentVaccination, updateAppointmentVaccination, cancelAppointment, vaccinate } from "@/api/appointment/appointmentVaccination";
import { listVaccine } from "@/api/vaccine/vaccine";
export default {
  name: "AppointmentVaccination",
  dicts: ['appointment_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约接种记录表格数据
      appointmentVaccinationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,  // 新增
        userIdCard: null, // 新增
        userEmail: null,  // 新增
        vaccineId: null,
        appointmentTime: null,
        location: null,
        status: null,
        vaccinationDate: null,
        batchNumber: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        vaccineId: [
          { required: true, message: "疫苗ID不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "预约人姓名不能为空", trigger: "blur" }
        ],
        userIdCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          //{ pattern: /^[1-9]\d{16}[\dXx]$/, message: "请输入有效的身份证号", trigger: "blur" }
        ],
        userEmail: [
          { type: "email", message: "请输入有效的邮箱地址", trigger: "blur" }
        ],
        appointmentTime: [
          { required: true, message: "预约时间不能为空", trigger: "blur" }
        ],
        location: [
          { required: true, message: "接种地点不能为空", trigger: "blur" }
        ],
      },
      // 添加疫苗列表数据
      vaccineOptions: [],
      // 接种弹窗显示状态
      vaccinateOpen: false,
      // 接种表单参数
      vaccinateForm: {
        recordId: null,
        batchNumber: null,
        vaccinationDate: null
      },
      // 接种表单校验规则
      vaccinateRules: {
        batchNumber: [
          { required: true, message: "疫苗批次号不能为空", trigger: "blur" }
        ],
        vaccinationDate: [
          { required: true, message: "接种时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // 添加获取疫苗列表的调用
    this.getVaccineList();
  },
  methods: {
    /** 查询预约接种记录列表 */
    getList() {
      this.loading = true;
      listAppointmentVaccination(this.queryParams).then(response => {
        this.appointmentVaccinationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        userName: null,
        userIdCard: null,
        userEmail: null,
        vaccineId: null,
        appointmentTime: null,
        location: null,
        status: '0', // 设置默认状态为待接种
        userId: this.$store.state.user.userId // 添加默认用户ID
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "疫苗预约";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getAppointmentVaccination(recordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.form.userId) {
            this.form.userId = this.$store.state.user.userId;
          }
          if (this.form.recordId != null) {
            updateAppointmentVaccination(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAppointmentVaccination(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除预约接种记录编号为"' + recordIds + '"的数据项？').then(function() {
        return delAppointmentVaccination(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('appointment/appointmentVaccination/export', {
        ...this.queryParams
      }, `appointmentVaccination_${new Date().getTime()}.xlsx`)
    },
    /** 获取疫苗列表 */
    getVaccineList() {
      listVaccine({
        pageNum: 1,
        pageSize: 100
      }).then(response => {
        this.vaccineOptions = response.rows.map(item => ({
          label: item.name,
          value: item.vaccineId
        }));
      });
    },
    /** 根据疫苗ID获取疫苗名称 */
    getVaccineName(vaccineId) {
      const vaccine = this.vaccineOptions.find(item => item.value === vaccineId);
      return vaccine ? vaccine.label : vaccineId;
    },
    /** 取消预约操作 */
    handleCancel(row) {
      this.$modal.confirm('是否确认取消该预约？').then(() => {
        return cancelAppointment(row.recordId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消预约成功");
      }).catch(() => {});
    },
    /** 接种按钮操作 */
    handleVaccinate(row) {
      this.vaccinateForm.recordId = row.recordId;
      this.vaccinateOpen = true;
    },
    // 取消接种
    cancelVaccinate() {
      this.vaccinateOpen = false;
      this.vaccinateForm = {
        recordId: null,
        batchNumber: null,
        vaccinationDate: null
      };
      this.resetForm("vaccinateForm");
    },
    /** 提交接种表单 */
    submitVaccinateForm() {
      this.$refs["vaccinateForm"].validate(valid => {
        if (valid) {
          vaccinate(this.vaccinateForm).then(response => {
            this.$modal.msgSuccess("接种成功");
            this.vaccinateOpen = false;
            this.getList();
          });
        }
      });
    }
  }
};
</script>
